# -*- coding: utf-8 -*-
import pandas as pd
from docx import Document
from docx.shared import Inches, Cm
from PIL import Image, ImageDraw, ImageFont
# from docx.enum.section import WD_ORIENTATION


g_tech = "name"


def mpix(v, dpi=300):
    return int(v * (dpi / 25.4))


def read_sheet(ret, file_path, i):
    df = pd.read_excel(file_path, sheet_name=i)

    for index, row in df.iterrows():
        sn = "%s" % row["sn"]
        sn = sn.strip()

        name = "%s" % row["name"]
        name = name.strip()

        cl = "%s" % row["cl"]
        cl = cl.strip()

        ret.append({
            "sn": sn,
            "name": name,
            "cl": cl,
            })


if __name__ == '__main__':
    file_path = "./%s.xlsx" % g_tech

    doc = pd.ExcelFile(file_path)

    ret = []

    for i in doc.sheet_names:
        read_sheet(ret, file_path, i)

    w = 30
    h = 20 * 0.618

    ret_pic = []

    for d in ret:
        cl = d["cl"]
        sn = d["sn"]
        name = d["name"]

        r = int(cl[0:3])
        g = int(cl[3:6])
        b = int(cl[6:9])

        color = (r, g, b)
        bg = Image.new('RGB', (mpix(w), mpix(h)), color=color)

        bg_w, bg_h = bg.size

        draw = ImageDraw.Draw(bg)

        f_x = mpix(2)
        f_y = mpix(2)

        fill = "black"

        font = ImageFont.truetype("font.ttc", size=50)
        draw.text((f_x, f_y), name, fill=fill, font=font)

        f_y = mpix(7)

        fill = "white"

        font = ImageFont.truetype("hb.ttf", size=20)
        draw.text((f_x, f_y), sn, fill=fill, font=font)

        bg.save("./pic/%s.png" % (sn))

        ret_pic.append(sn)

    dc = Document()

    section = dc.sections[0]
    section.page_height = Inches(11.7)
    section.page_width = Inches(8.3)

    section.top_margin = Cm(0.5)
    section.bottom_margin = Cm(0.5)
    section.left_margin = Cm(0.5)
    section.right_margin = Cm(0.5)
    # section.orientation = WD_ORIENTATION.LANDSCAPE

    for d in ret_pic:
        path = "./pic/%s.png" % d
        dc.add_picture(path, width=Inches(3.69))

    dc.save("./tag.docx")
